﻿using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;

namespace Microsoft.AspNetCore.App
{
    /// <summary>
    /// 用于构建管道
    /// </summary>
    public interface IApplicationBuilder
    {
        IServiceProvider ApplicationServices { get; }
        void Use(Func<RequestDelegate, RequestDelegate> middleware);
        RequestDelegate Build();
    }

    public class ApplicationBuilder : IApplicationBuilder
    {
        private List<Func<RequestDelegate, RequestDelegate>> _middlewares = new();

        public IServiceProvider ApplicationServices { get; }

        public ApplicationBuilder(IServiceProvider services)
        {
            ApplicationServices = services;
        }

        /// <summary>
        /// 管道构建算法
        /// </summary>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public RequestDelegate Build()
        {
            RequestDelegate app = context =>
            {
                if (!context.Response.HasStartd)
                {
                    context.Response.StatusCode = 404;
                }
                return Task.CompletedTask;
            };
            for (int i = _middlewares.Count - 1; i > -1; i--)
            {
                app = _middlewares[i](app);
            }
            return app;
        }

        /// <summary>
        /// 注册中间件
        /// </summary>
        /// <param name="middleware"></param>
        public void Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            _middlewares.Add(middleware);
        }
    }


}
